package com.nanxhs.concurrent.thread.pause;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 使用suspend与resume 挂起/唤醒线程例子
 *
 * @author: haibin.tang
 * @date: 2021/1/28
 */
public class SuspendSample {

    private static final Queue<Integer> SEQUENCE_QUEUE = new LinkedBlockingDeque<>();

    private Thread productionThread;
    private Thread consumerThread;

    private void productionThread() {
        productionThread = new Thread(() -> {
            while (true) {
                int code = (int)(Math.random() * 10000);
                SEQUENCE_QUEUE.add(code);
                System.out.println(Thread.currentThread().getName() + "-生产序号 -->>> " + code);
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
                if (SEQUENCE_QUEUE.size() > 2) {
                    consumerThread.resume();
                    productionThread.suspend();
                }
            }
        });
    }

    private void consumerThread() {
        consumerThread = new Thread(() -> {
           while (true) {
               if (SEQUENCE_QUEUE.size() < 1) {
                   productionThread.resume();
                   consumerThread.suspend();
               }
               System.out.println(Thread.currentThread().getName() + "-消费序号 -->>> " + SEQUENCE_QUEUE.poll());
               LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
           }
        });
    }

    public static void main(String[] args) {
        SuspendSample suspendSample = new SuspendSample();
        suspendSample.productionThread();
        suspendSample.consumerThread();
        suspendSample.productionThread.start();
        suspendSample.consumerThread.start();
    }
}
